
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package war;

import ejb.Outfit;
import ejb.OutfitFacadeLocal;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import session.GestOutfitLocal;

/**
 *
 * @author Gianna
 */
@WebServlet(name = "servletoutfit", urlPatterns = {"/servletoutfit"})

@MultipartConfig
public class servletoutfit extends HttpServlet {

    @EJB
    private OutfitFacadeLocal outfitFacade;
    @EJB
    private GestOutfitLocal gestOutfit;

    private static final String SAVE_DIR = "images/outfit";

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession(true);
        try {

            String of = request.getParameter("of");

            if (of.equals("outfit")) {

                List<Outfit> listagallery = gestOutfit.findAll();
                ServletContext sc = getServletContext();
                RequestDispatcher rd = sc.getRequestDispatcher("/gallery.jsp");

                request.setAttribute("listagallery", listagallery);
                rd.forward(request, response);
            }

            if (of.equals("aggiungicanvas")) {
                String idUtente = session.getAttribute("mail").toString();
                char[] base64 = request.getParameter("file").toCharArray();
                gestOutfit.addOutfit(idUtente, null, base64);
                
                ServletContext sc = getServletContext();
                RequestDispatcher rd = sc.getRequestDispatcher("/index.jsp");
                rd.forward(request, response);


            }

            if (of.equals("aggiungioutfit")) {
                String idUtente = session.getAttribute("mail").toString();
                Part p1 = request.getPart("file");
                String outfit = extractFileName(p1);

                gestOutfit.addOutfit(idUtente, outfit, null);

                // gets absolute path of the web application
                String appPath = getServletContext().getRealPath("");
                // constructs path of the directory to save uploaded file
                String savePath = appPath + File.separator + SAVE_DIR;

                // creates the save directory if it does not exists
                File fileSaveDir = new File(savePath);
                if (!fileSaveDir.exists()) {
                    fileSaveDir.mkdir();
                }

                InputStream is = p1.getInputStream();
                String outputfile = "C:/Users/Gemma/Documents/NetBeansProjects/fashion-project/WhatToWear-war/web/images/outfit/";  // get path on the server
                outputfile += outfit;
                FileOutputStream os = new FileOutputStream(outputfile);
                // write bytes taken from uploaded file to target file
                int ch = is.read();
                while (ch != -1) {
                    os.write(ch);
                    ch = is.read();
                }
                os.close();
                System.out.println(outputfile);

                /*for (Part part : request.getParts()) {
                 String fileName = extractFileName(part);
                 System.out.println(fileName);
                 part.write(savePath + File.separator + fileName);
                 }*/
                /*
                 request.setAttribute("message", "Upload has been done successfully!");
                 getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
                 */
                ServletContext sc = getServletContext();
                RequestDispatcher rd = sc.getRequestDispatcher("/index.jsp");
                rd.forward(request, response);

            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    /**
     * Extracts file name from HTTP header content-disposition
     */
    private String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if (s.trim().startsWith("file")) {
                return s.substring(s.indexOf("=") + 2, s.length() - 1);
            }
        }
        return "";
    }
}
